package com.hyfd.deal.Flow;

import java.net.SocketTimeoutException;
import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.hyfd.common.GenerateData;
import com.hyfd.common.utils.MD5;
import com.hyfd.common.utils.MapUtils;
import com.hyfd.common.utils.ToolDateTime;
import com.hyfd.common.utils.ToolHttp;
import com.hyfd.common.utils.XmlUtils;
import com.hyfd.deal.BaseDeal;

/**
 * zhitong单号码流量充值接口
 * 
 * @author cxj
 *
 */
public class WangSenFlowDeal implements BaseDeal
{
    Logger log = Logger.getLogger(getClass());
    
    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> deal(Map<String, Object> order)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        int flag = -1;
        
        try
        {
            // 命令
            String Action = "flowRecharge";
            // 版本号
            String V = "1.1";
            // 手机号
            String Mobile = (String)order.get("phone");
            // 平台订单号
            String OutTradeNo =
                ToolDateTime.format(new Date(), "yyyyMMddHHmmssSSS") + Mobile + GenerateData.getIntData(9, 4);
            map.put("orderId", OutTradeNo);
            // 账号
            Map<String, Object> channel = (Map<String, Object>)order.get("channel");// 获取通道参数
            String linkUrl = (String)channel.get("link_url");// 充值地址
            String defaultParameter = (String)channel.get("default_parameter");// 默认参数
            Map<String, String> paramMap = XmlUtils.readXmlToMap(defaultParameter);
            String Account = paramMap.get("Account");// 账户名
            String apiKey = paramMap.get("apiKey");// 平台的appKey
            // 0 漫游流量 1非漫游流量，不带改参数时默认为0
            String range = paramMap.get("type");
            // 套餐
            String spec = new Double(order.get("value") + "").intValue() + "";
            String Package = "YD" + spec;
            // 计算签名
            String md5Str = "account=" + Account + "&mobile=" + Mobile + "&package=" + Package + "&key=" + apiKey;
            String sign =MD5.ToMD5(md5Str);//getMD5(md5Str,"utf-8");
            // 组装参数
            String param =
                "V=" + V + "&Action=" + Action + "&OutTradeNo=" + OutTradeNo + "&Account=" + Account + "&Mobile="
                    + Mobile + "&Package=" + Package + "&Sign=" + sign;
            String contentType = "application/x-www-form-urlencoded";
            // post请求
            String result = ToolHttp.post(false, linkUrl, param, contentType);
            // 判断是否成功
            if (result != null)
            {
                JSONObject jObject = JSONObject.parseObject(result);
                String taskId = jObject.getString("TaskID");
                map.put("providerOrderId", taskId);
                String code = jObject.getString("Code");
                String message = jObject.getString("Message");
                map.put("resultCode", code + ":" + message);
                if ("0".equals(code))
                {
                    flag = 1;
                }
                else
                {
                    flag = 0;
                }
            }
        }
        catch (ConnectTimeoutException | SocketTimeoutException e)
        {// 请求、响应超时
            flag = -1;
        }
        catch (Exception e)
        {
            log.error("王森流量出错" + e + MapUtils.toString(order));
        }
        map.put("status", flag);
        return map;
    }
    
 // 与ASP兼容的MD5加密算法
    public static String getMD5(String str, String encoding)
        throws Exception
    {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes(encoding));
        byte[] result = md.digest();
        StringBuffer sb = new StringBuffer(32);
        for (int i = 0; i < result.length; i++)
        {
            int val = result[i] & 0xff;
            if (val < 0xf)
            {
                sb.append("0");
            }
            sb.append(Integer.toHexString(val));
        }
        return sb.toString().toUpperCase();
    }
}
